<?php

namespace Core\Sign;

use Core\Enums\ErrorEnum;
use Core\Result\Result;

class Sign
{
    private $sign = "d52diBKdDshHRhSWsEfwP7wlQ=";
    /**
     * 加密
     */
    public function encryptionToken($token){
        $info = $token. '-' .$this->getTime().'-'.$this->getEndTime($this->getTime());//设置token
        $signature = hash_hmac('md5',$info,$this->sign);
        return $info . '-' . $signature;
    }
    /**
     * 解密
     */
    public function decryptToken($sign){
        $signData = explode("-",$sign);
        if(count($signData) != 4){
            Result::error(ErrorEnum::DECRYPTTOKENERROR);
        }
        if($signData[0]==null){
            Result::error(ErrorEnum::DECRYPTTOKNULL);
        }
        /*if($signData[2]!=null && $this->getTime()>$signData[2]){
            Result::error(ErrorEnum::DECRYPTTOKENOVERTIME);
        }*/
        $info = $signData[0]. '-' .$signData[1]. '-' .$signData[2];
        $signature = hash_hmac('md5',$info,$this->sign);
        if($signature != $signData[3]){
            Result::error(ErrorEnum::DECRYPTTOKEDECRYPT);
        }
        return $signData[0];
        //return \ResultData::resData("200","解密成功",null);
    }
    /**
     * 过期时间为7天
     */
    private function getEndTime($time){
        return $time +604800;
    }
    private function getTime(){
        return time();
    }
}